#include <func.h>

typedef struct
{
    int id;
    int money;
} Account;

Account acct1 = {1, 100};
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;

void* start_routine(void* arg)
{
    int err;
    Account* acct = (Account*)arg;
    sleep(1);
    err = pthread_mutex_lock(&mtx);
    if(err)
        error(1, err, "pthread_mutex_lock");

    if(acct->money == 0)
    {
        fprintf(stderr, "Account empty 0x%lu exit\n", pthread_self());

        err = pthread_mutex_unlock(&mtx);
        if(err)
            error(1, err, "pthread_mutex_unlock");
       
        return NULL;
    }    
    else
    {
        acct->money = 0;
        fprintf(stderr, "0x%lu get 100 money\n", pthread_self());
        
        err = pthread_mutex_unlock(&mtx);
        if(err)
            error(1, err, "pthread_mutex_unlock");
        
        return NULL;
    }

}

int main(void)
{
    pthread_t arr[10];
    for(int i = 0; i < 10; ++i)
        pthread_create(arr + i, NULL, start_routine, (void*)&acct1);

    for(int i = 0; i < 10; ++i)
        pthread_join(arr[i], NULL);

    return 0;
}

